<?php
/**
 * PHP飞信发送类
 * @author hexh
 * @version 1.2.1
 */
 
require 'PHPFetion.php';
require 'ShmCache.php';

class MyFetion extends PHPFetion
{
	/**
     * 是否注销
     * @var array
     */
	public $_userlogout = true;
	
	/**
     * Uid-mobile缓存
     * @var array
     */
    protected $_mobiles = array();
	
	/**
	 * Cookies缓存的shm编号
	 *
	 */
	protected $_shmNo = 34223;
	
	/**
	 * 添加飞信好友
	 * @param string $mobile 好友手机号
	 * @return string
	 */
	public function addFriend($addmobile, $nickname){
		
		$uri = '/im/user/insertfriendsubmit.action';
		$data = 'type=0&nickname='.$nickname.'&number='.$addmobile;
		$result = $this->_postWithCookie($uri, $data);
		
		return $result;
	}
	
	/**
	 * 删除飞信好友
	 * @param string $mobile 好友手机号
	 * @return string
	 */
	public function delFriend($mobile){
		$uid = $this->_getUid($mobile);
        return $uid === '' ? '-9002, 号码['.$mobile.']不在好友列表中.' : $this->_delByUid($uid);
	}
	
	public function getMsg()
	{
		return $this->_getMsg();
	}
	
	/**
     * 删除飞信好友
     * @param string $uid 飞信ID
     * @return string
     */
    protected function _delByUid($uid)
    {
        $uri = '/im/user/deletefriendsubmit.action';
		$data = 'touserid='.$uid;
        $result = $this->_postWithCookie($uri, $data);        
        return $result;
    }
	
	/**
     * 读取飞信信息
     * @return string
     */
	protected function _getMsg()
	{
		$uri = '/im/box/alllist.action';
        $result = $this->_postWithCookie($uri, '');
		//$result='toinputMsg.action?touserid=8991238;dsfdf;toinputMsg.action?touserid=88888;toinputMsg.action?touserid=123456789';
		
		preg_match_all('/toinputMsg\.action\?touserid=(\d+)/si', $result, $matches);
		for ($i = 0; $i < count($matches[1]); $i++) {
			$touid = $matches[1][$i];
			echo $touid.'<br>';
			$chaturi = '/im/chat/toinputMsg.action?box=true';
			$chatdata = 'touserid='.$touid;
			$chatret = $this->_postWithCookie($chaturi, $chatdata);
			echo '<br>-----------<br>'.$chatret;
			preg_match_all('/[新](.*)[d{2}:d{2}]/si', $result, $matches);
			
		}
        return $matches;
	}
	
	/**
     * 飞信ID获取手机号
     * @param string $mobile 手机号
     * @return string
     */
    protected function _getMobile($uid)
    {
        if (empty($this->_mobiles[$uid]))
        {
            $uri = '/im/user/userinfoByuserid.action';
            $data = 'touserid='.$uid;
            $result = $this->_postWithCookie($uri, $data);
            
            //匹配
			preg_match('手机号码:(\d+)/si', $result, $matches);
            $this->_uids[$mobile] = isset($matches[1]) ? $matches[1] : '';
        }
        return $this->_mobiles[$uid];
    }
	
	public function test()
	{
		return $this->testCookie();
	}
	
	public function testCookie()
	{
		
		$this->_setCookie('m13713393257', 'abcdcookie...');
		
		$shmcache = new ShmCache($this->_shmNo);
		echo '<br>######'.$this->_getCookie('m13713393257');
		
		$storedarray = (array)json_decode($shmcache->read());
		print_r($storedarray);
		$shmcache->close();
	}
	
	
	public function testSHM()
	{
		$results = array(
			'user' => 'John',
			'password' => '12223',
			'posts' => array('My name is John', 'My name is not John')
		);
		$results['m13713393257'] = @'!@#)*)JFLKDSJFOWEUR-09-234kdvm.xc,mv2394;lkdfk)_(_!@$Lk;dfkds-23';

		$data = json_encode($results);
		$shmno=34123;
		$shmcache = new ShmCache($shmno);
		$shmcache->write($data);
		$storedarray = (array)json_decode($shmcache->read());
		print_r($storedarray);
		echo '<br><br>';
		echo isset($storedarray['m13713393257']) ? $storedarray['m13713393257'] : '不存在!';

		echo '<br><br><br>'.$shmcache->shmid;

	}
	
	/**
     * 读取Shm 根据手机号返回已登录cookie
     * @return string
     */
	protected function _getCookie($mobile)
	{
		$shmcache = new ShmCache($this->_shmNo);
		$storedCookies = (array)json_decode($shmcache->read());
		if ($storedCookies === '')
			return '';
		return isset($storedCookies[$mobile]) ? $storedCookies[$mobile] : '';
	}
	
	/**
     * 更新Shm 保存已登录cookie
     * @return string
     */
	protected function _setCookie($mobile, $cookie)
	{
		$shmcache = new ShmCache($this->_shmNo);
		$storedCookies = (array)json_decode($shmcache->read());
		$oldCookie = isset($storedCookies[$mobile]) ? $storedCookies[$mobile] : '';
		if ($oldCookie != $cookie) {
			echo '<br>-----<br>newCookie:'.$cookie.'<br> oldCookie:'.$oldCookie;
			
			$storedCookies[$mobile] = $cookie;
			$data = json_encode($storedCookies);
			
			echo '<br>-----<br>data:'.$data.'<br>';
			
			$shmcache->write($data);
			$tt = (array)json_decode($shmcache->read());
			print_r('-----<br>+++++tt:'.$tt.'<br>');
		}
	}
	
	/**
     * 登录
     * @return string
     */
    protected function _login()
    {
		$storedCookie = $this->_getCookie($this->_mobile);
		if ($storedCookie != '' )
		{
			$this->_cookie = $storedCookie;
			$chkresult = $this->_postWithCookie('/im/login/cklogin.action', '');
			if (!$chkresult) {
				$this->_cookie = '';
			}
		}
		$result = $this->_loginnew();
		if ($result) {
			$this->_setCookie($this->_mobile, $this->_cookie);
		}
    }
	
	/**
     * 登录
     * @return string
     */
	protected function _loginnew()
    {
		if ( $this->_cookie === '') {
			$uri = '/huc/user/space/login.do?m=submit&fr=space';
			$data = 'mobilenum='.$this->_mobile.'&password='.urlencode($this->_password);
			$result = $this->_postWithCookie($uri, $data);

			//解析Cookie
			preg_match_all('/.*?\r\nSet-Cookie: (.*?);.*?/si', $result, $matches);
			if (isset($matches[1]))
			{
				$this->_cookie = implode('; ', $matches[1]);
			}
		}
        $result = $this->_postWithCookie('/im/login/cklogin.action', '');
        return $result;
	}
	
	/**
     * 析构函数
     */
    public function __destruct()
    {
		if ( $this->_userlogout ) {
			$this->_logout();
		}
    }
}
